import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JOptionPane;

public class DataCollector extends ClipboardHandler {
	private HashMap<String, Integer> history;
	private String path;
	private Pattern p = Pattern.compile("^\\s*时间\\s+开盘价\\s+最高价\\s+最低价\\s+收盘价\\s+成交量\\s+额\\(持仓\\)\\s+上涨家数\\s+下跌家数\\s*[\\r\\n]+(.+?)[\\r\\n]");
	private String getDigest(String content) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(content.getBytes());
			return md.toString();
		} catch (NoSuchAlgorithmException e) {
			return String.format("%x", content.hashCode());
		}
	}
	private String getFileNameByTimestamp() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss");
		return sdf.format(new Date()) + ".txt";
	}
	private boolean save(String fn, String content) {
		try {
			BufferedWriter out = new BufferedWriter(new FileWriter(fn));
			out.write(content);
			out.close();	
	        return true;
		} catch (IOException e) {
			log.warning("Exception raised when saving clipboard content to: " + fn);
			log.warning(e.getMessage());
			return false;
		}
	}
	@Override
	public boolean processContent() {
		String content = getText();
	    String digest = getDigest(content);
		if (history.containsKey(digest)) return false;
		history.put(digest, 1);
		Matcher m = p.matcher(content);
		if (m.find()) {
			String sample = m.group(1);
			String[] segs = sample.split("\\s+");
			String dest = path + ((segs.length == 10) ? "min" : "day") + File.separator;
			String fn = dest + getFileNameByTimestamp();  
			save(fn, content);
			JOptionPane.showMessageDialog(null, "Data successfully saved");
			return true;
		} else {
			File dir = new File(path + "min" + File.separator);
			File[] data = dir.listFiles();
			long lastModified = 0;
			for (File f : data) {
				long modified = f.lastModified();
				if (modified > lastModified) lastModified = modified;
			}
			Date now = new Date();
			long elapsed = now.getTime() - lastModified; 
			if (elapsed > 600000000) {
				String days = String.format("Data has not been saved for about %0.2f days", (elapsed / 86400000.0));
				log.severe(days);
				JOptionPane.showMessageDialog(null, days, "Warning", JOptionPane.WARNING_MESSAGE);	
			}
			return false;
		}
	}
	public boolean initialize() {
		path = env.getProperty("path", "");
		if (path.isEmpty()) {
			log.fine("DataCollector: path not set, cannot proceed");
			return false;
		}
		if (!path.endsWith(File.separator)) path += File.separator;
		File min = new File(path + "min");
		if (!min.isDirectory()) {
			if (!min.mkdirs()) {
				log.fine("DataCollector: cannot create path to store data (min)");
				return false;
			}
		}
		File day = new File(path + "day");
		if (!day.isDirectory()) {
			if (!day.mkdirs()) {
				log.fine("DataCollector: cannot create path to store data (day)" );
				return false;
			}
		}
		log.info("Message from environment: " + env.getProperty("path", "n/a"));
		history = new HashMap<String , Integer>();
		return true;
	}
}